package dse.messages.multiversion;

import dse.DataObject;
import dse.DataShare;
import dse.Experiment;
import dse.ExperimentRecorder;
import dse.Node;
import dse.Version;
import dse.messages.Message;
import dse.messages.MessageHandler;
import dse.messages.MessageSender;
import dse.messages.MessageType;

public class RequestVersionShareMessageHandler extends MessageSender implements
		MessageHandler {
	private DataObject dobj;
	private Version version;
	private SVRHandler handler;
	private int round;

	public RequestVersionShareMessageHandler(Experiment experiment, DataObject dobj, 
			Version version, SVRHandler handler, int round) {
		super(experiment);
		// TODO Auto-generated constructor stub
		this.dobj = dobj;
		this.version = version;
		this.handler = handler;
		this.round = round;
	}

	@Override
	public boolean acceptMessage(Message message) {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public void messageInterupted(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		if(ExperimentRecorder.debug)
			recorder.debug(this, "msgIntrpt: " + message, time);
		handler.readVersion(recorder, message.from(), null, time, round);
	}

	@Override
	public void messageReceived(ExperimentRecorder recorder, Message message,
			double time) {
		// TODO Auto-generated method stub
		if(ExperimentRecorder.debug)
			recorder.debug(this, "msgRcvd: " + message, time);
		if (message.messageType() != MessageType.RequestVersionShare) {
			recorder.warn(
					"RequestVersionShareMessageHandler recieved " + 
					message.messageType() + " message."
					);
			return;
		}			
		// What do we know about the share?
		Node receiver = message.to();
		
		// Does the receiver have the share?
		DataShare share = receiver.getDataShare(dobj);
		if (share != null)
		{
			// Then we need to send a new message BACK (thats why to and from
			// are reversed!
			Version v = share.getDesignatedVersion(version);
			Message m = super.createVersionShareResponseMessage(receiver, message.from(), dobj, v, round,
					message.purpose(), handler);
			if(ExperimentRecorder.debug)
				recorder.debug(this, "new msg: " + m, time);
			experiment.messageQueue().enqueueMessage(m, time);
		}
		else
		{
			this.messageInterupted(recorder, message, time);
		}
	}
}
